package com.zysf.library_boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zysf.library_boot.dto.BookCollect;
import com.zysf.library_boot.dto.CollectDto;
import com.zysf.library_boot.dto.ReaderLendDto;
import com.zysf.library_boot.entity.Collect;
import com.zysf.library_boot.service.BookInfoService;
import com.zysf.library_boot.service.CollectService;
import com.zysf.library_boot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    private CollectService collectService;

    @Autowired
    private BookInfoService bookInfoService;

    @RequestMapping("/changeCollect")
    public Result changeCollect(Collect collect){
        // 判断数据库中是否存在当前用户和当前电影的收藏记录
        QueryWrapper<Collect> qw = new QueryWrapper<>();
        qw.eq("readerid", collect.getReaderid());
        qw.eq("bookid", collect.getBookid());
        Collect collectRes  =  collectService.getOne(qw);
        if(collectRes == null){ // 记录不存在
            collectService.save(collect); // 收藏
        } else { // 记录存在
            collectService.removeById(collectRes.getCid()); // 取消收藏
        }
        return Result.ok(collectRes);
    }

    @RequestMapping("/getCollect")
    public Result getCollect(Collect collect){
        // 判断数据库中是否存在当前用户和当前电影的收藏记录
        QueryWrapper<Collect> qw = new QueryWrapper<>();
        qw.eq("readerid", collect.getReaderid());
        qw.eq("bookid", collect.getBookid());
        Collect collectRes  =  collectService.getOne(qw);
        return Result.ok(collectRes);
    }

    @RequestMapping("/countCollect")
    public Result countCollect(Integer bookid){
        QueryWrapper<Collect> qw = new QueryWrapper<>();
        qw.eq("bookid", bookid);
        long count = collectService.count(qw);
        return Result.ok(count);
    }

    @RequestMapping("/getBookCollect")
    public Result getBookCollect(@RequestParam Integer id, @RequestParam int currentPage, @RequestParam int pageSize) {
        Page<BookCollect> page = new Page<>(currentPage, pageSize);
        IPage<BookCollect> bookCollectPage = collectService.getReaderBookCollect(id, page);

        Map<String, Object> result = new HashMap<>();
        result.put("records", bookCollectPage.getRecords());
        result.put("total", bookCollectPage.getTotal());

        return Result.ok(result);
    }

}

